<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="small" @click="handleAdd"
                   v-hasPermi="['travel:schedule:add']">新增
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="咨询号" prop="travelConsult">
        <el-input v-model="queryParams['travelConsult.consultNumber']" placeholder="请输入咨询号" clearable
                  @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="手机号" prop="travelClient">
        <el-input v-model="queryParams['travelClient.clientTel']" placeholder="请输入手机号" clearable
                  @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option v-for="dict in dict.type.travel_schedule_status" :key="dict.value" :label="dict.label"
                     :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">查询</el-button>
         <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="scheduleList" @selection-change="handleSelectionChange">
<!--      <el-table-column label="序号" align="center" prop="scheduleId" type="index" />-->
      <el-table-column label="序号" align="center" :width="60">
        <template slot-scope="scope">
          <!-- 公式：(当前页-1) * 每页条数 + 当前行索引 + 1 -->
          {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="行程单号" align="center" prop="scheduleNumber" :width="170" />
      <el-table-column label="咨询号" align="center" prop="travelConsult.consultNumber" :width="170" />
      <el-table-column label="客户姓名" align="center" prop="travelClient.clientName" />
      <el-table-column label="手机号" align="center" prop="travelClient.clientTel" :width="110"/>
      <el-table-column label="出行人数" align="center" prop="travelConsult.travelerCount"  />
      <el-table-column label="出发时间" align="center" prop="travelConsult.estimatedTime" :width="100"/>
      <el-table-column label="计划天数" align="center" prop="travelConsult.plannedDays" />
      <el-table-column label="出行费用" align="center" prop="travelMoneyTotal" />
      <el-table-column label="服务费用" align="center" prop="serviceMoneyTotal" />
      <el-table-column label="定制师" align="center">
        <template slot-scope="scope">
          <!-- 从映射中获取姓名，默认显示"未分配" -->
          {{ designerNameMap[scope.row.travelConsult.designerId] || '未分配' }}
        </template>
      </el-table-column>
      <el-table-column label="地陪" align="center">
        <template slot-scope="scope">
          {{ getGuideName(scope.row.guideId) }}
        </template>
      </el-table-column>

      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.travel_schedule_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!-- 查看详情按钮 - 多个角色在不同状态下可看 -->
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleDetail(scope.row)"
                     v-if="showDetailButton(scope.row)">详情
          </el-button>

          <!-- 修改按钮 - 定制师在草稿状态可看 -->
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-if="showEditButton(scope.row)">修改
          </el-button>

          <!-- 删除按钮 - 定制师在草稿状态可看 -->
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-if="showDeleteButton(scope.row)">删除
          </el-button>

          <!-- 提交按钮 - 定制师在草稿状态可看 -->
          <el-button size="mini" type="text" icon="el-icon-upload" @click="handleSubmit(scope.row)"
                     v-if="showSubmitButton(scope.row)">提交
          </el-button>

          <!-- 退回按钮 - 客服在待签约状态可看 -->
          <el-button size="mini" type="text" icon="el-icon-refresh-left" @click="handleReject(scope.row)"
                     v-if="showRejectButton(scope.row)">退回
          </el-button>

          <!-- 签约按钮 - 客服在待签约状态可看 -->
          <el-button size="mini" type="text" icon="el-icon-check" @click="handleSign(scope.row)"
                     v-if="showSignButton(scope.row)">签约
          </el-button>

          <!-- 分配地陪按钮 - 客服在待签约状态可看 -->
          <el-button size="mini" type="text" icon="el-icon-user" @click="handleDesigner(scope.row)"
                     v-if="showAssignButton(scope.row)">地陪
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getList" />

    <!-- 添加或修改详情行程管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" :model="dialogForm" :rules="rules" label-width="100px">
        <el-row :gutter="15" class="mb8">
          <!-- 第一行：咨询号、姓名、手机号 -->
          <el-col :span="8">
            <el-form-item label="咨询号" prop="travelConsult.consultNumber">
              <el-input v-model="dialogForm.travelConsult.consultNumber" placeholder="请选择咨询号" clearable
                        @click.native="openConsultDialog" :disabled="isDetailMode || !!dialogForm.scheduleId" style="width: 260px;" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="姓名" prop="travelClient.clientName" label-width="80px">
              <el-input v-model="dialogForm.travelClient.clientName" clearable disabled style="width: 260px;" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="手机号" prop="travelClient.clientTel">
              <el-input v-model="dialogForm.travelClient.clientTel" clearable disabled style="width: 260px;" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="15" class="mb8">
          <!-- 第二行：出行人数、意向目的地、预算 -->
          <el-col :span="8">
            <el-form-item label="出行人数" prop="travelConsult.travelerCount">
              <el-input v-model="dialogForm.travelConsult.travelerCount" clearable disabled style="width: 260px;" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="意向目的地" prop="travelConsult.preferredDestination" label-width="10">
              <el-input v-model="dialogForm.travelConsult.preferredDestination" clearable disabled
                        style="width: 260px;" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="预算" prop="travelConsult.budget">
              <el-input v-model="dialogForm.travelConsult.budget" clearable disabled style="width: 260px;" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="15" class="mb8">
          <!-- 第三行：预计出发时间、可调整时间、出行天数 -->
          <el-col :span="8">
            <el-form-item label="预计出发时间" prop="travelConsult.estimatedTime" label-width="10">
              <el-input v-model="dialogForm.travelConsult.estimatedTime" clearable disabled style="width: 260px;" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="可调整时间" prop="travelConsult.flexibleDays" label-width="10">
              <el-input v-model="dialogForm.travelConsult.flexibleDays" clearable disabled style="width: 260px;" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="出行天数" prop="travelConsult.plannedDays">
              <el-input v-model="dialogForm.travelConsult.plannedDays" clearable disabled style="width: 260px;" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 备注信息（来自travel_consult，独占一行且重点显示） -->
        <el-row class="mb8">
          <el-col :span="24">
            <el-form-item label="备注信息" prop="travelConsult.remark" label-class-name="bold-label">
              <el-input v-model="dialogForm.travelConsult.remark" type="textarea" rows="3" disabled
                        style="font-size: 14px; border: 1px solid #409EFF; width: 1046px;" />
            </el-form-item>
          </el-col>
        </el-row>

        <div class="dynamic-schedule-wrapper">
          <!-- 固定的费用区域 -->
          <div class="total-fee-container">
            <hr>
            <!-- 新增：费用合计区域 -->
            <el-row :gutter="15" class="total-fee-container" style="margin: 15px 0;">
              <el-col :span="8">
                <el-form-item label="旅行费用合计">
                  <el-input v-model="dialogForm.travelMoneyTotal" readonly placeholder="0.00"
                            prefix-icon="el-icon-money" style="width:200px;"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="服务费用合计">
                  <el-input v-model="dialogForm.serviceMoneyTotal" readonly placeholder="0.00"
                            prefix-icon="el-icon-money" style="width:200px;"/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="费用总计">
                  <el-input v-model="dialogForm.moneyTotal" readonly placeholder="0.00" prefix-icon="el-icon-money"
                            style="font-weight: bold; width:200px;" />
                </el-form-item>
              </el-col>
            </el-row>
            <hr>
          </div>
          <!-- 当前步骤的行程内容表单 -->
          <!-- 所有行程内容表单，循环渲染 -->
          <div class="dynamic-schedule-content">
            <div v-for="(content, index) in dialogForm.scheduleContents" :key="content.scheduleContentId || index"
                 class="step-content" :id="`content-${index}`">
              <div style="display: flex; justify-content: space-between; align-items: center; margin-top: 20px;">
                <h1 style="margin: 10px 0">内容{{ index + 1 }}</h1>
              </div>

              <!-- 时间段（开始时间+结束时间 一行显示） -->
              <el-row :gutter="10" class="mb4">
                <el-col :span="12">
                  <el-form-item label="开始时间" :prop="`scheduleContents[${index}].startTime`"
                                :rules="rules.scheduleContentRules.startTime">
                    <el-date-picker v-model="content.startTime" type="datetime" placeholder="选择开始时间" style="width: 100%"   value-format="yyyy-MM-dd HH:mm:ss"

                                    :disabled="isDetailMode || !isConsultSelected" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="结束时间" :prop="`scheduleContents[${index}].endTime`"
                                :rules="rules.scheduleContentRules.endTime">
                    <el-date-picker v-model="content.endTime" type="datetime" placeholder="选择结束时间" style="width: 100%"   value-format="yyyy-MM-dd HH:mm:ss"
                                    :disabled="isDetailMode || !isConsultSelected" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-form-item label="行程详情" :prop="`scheduleContents[${index}].scheduleContent`"
                            :rules="rules.scheduleContentRules.scheduleContent">
                <el-input v-model="content.scheduleContent" type="textarea" rows="3" placeholder="输入行程具体内容"
                          :disabled="isDetailMode || !isConsultSelected" />
              </el-form-item>

              <!-- 图片上传部分 -->
              <el-form-item label="上传图片">
                <el-row :gutter="10">
                  <el-col :span="7">
                    <el-upload class="avatar-uploader" action="/dev-api/common/upload" :show-file-list="false"
                               :on-success="(response) => handleImageSuccess(response, index, 1)"
                               :before-upload="beforeImageUpload" :disabled="isDetailMode || !isConsultSelected">
                      <img v-if="content.picture1" :src="content.picture1" class="avatar">
                      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                  </el-col>
                  <el-col :span="8">
                    <el-upload class="avatar-uploader" action="/dev-api/common/upload" :show-file-list="false"
                               :on-success="(response) => handleImageSuccess(response, index, 2)"
                               :before-upload="beforeImageUpload" :disabled="isDetailMode || !isConsultSelected">
                      <img v-if="content.picture2" :src="content.picture2" class="avatar">
                      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                  </el-col>
                  <el-col :span="7">
                    <el-upload class="avatar-uploader" action="/dev-api/common/upload" :show-file-list="false"
                               :on-success="(response) => handleImageSuccess(response, index, 3)"
                               :before-upload="beforeImageUpload" :disabled="isDetailMode || !isConsultSelected">
                      <img v-if="content.picture3" :src="content.picture3" class="avatar">
                      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                  </el-col>
                </el-row>
              </el-form-item>

              <el-row :gutter="10" class="mb4">
                <el-col :span="12">
                  <el-form-item label="旅行费用" :prop="`scheduleContents[${index}].travelMoney`"
                                :rules="rules.scheduleContentRules.travelMoney">
                    <el-input v-model.number="content.travelMoney" placeholder="输入旅行费用" style="width: 100%"
                              :disabled="isDetailMode || !isConsultSelected" @blur="calculateTotalFees" type="number"
                              step="0.01" min="0" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="服务费用" :prop="`scheduleContents[${index}].serviceMoney`"
                                :rules="rules.scheduleContentRules.serviceMoney">
                    <el-input v-model.number="content.serviceMoney" placeholder="输入服务费用" style="width: 100%"
                              :disabled="isDetailMode || !isConsultSelected" @blur="calculateTotalFees" type="number"
                              step="0.01" min="0" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-form-item label="费用说明">
                <el-input v-model="content.remark" type="textarea" rows="2" placeholder="输入费用相关说明"
                          :disabled="isDetailMode || !isConsultSelected" />
              </el-form-item>
              <div class="content-actions">
                <!-- 只有内容数量大于1时显示删除按钮 第一个的时候不显示删除按钮-->
                <el-button
                  v-if="dialogForm.scheduleContents.length > 1 && index !== dialogForm.scheduleContents.length - 1"
                  type="danger" icon="el-icon-delete" size="mini" @click="deleteContent(index)"
                  :disabled="isDetailMode || !isConsultSelected">删除内容
                </el-button>

                <!-- 最后一个内容显示添加按钮 -->
                <el-button v-else-if="index === dialogForm.scheduleContents.length - 1" type="primary"
                           icon="el-icon-plus" size="mini" @click="addNewContent()"
                           :disabled="isDetailMode || !isConsultSelected || !isContentValid(index)">添加内容
                </el-button>
              </div>
              <hr v-if="index !== dialogForm.scheduleContents.length - 1">
            </div>
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitDialogForm" v-if="!isDetailMode">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 咨询选择对话框 -->
    <el-dialog title="选择咨询信息" :visible.sync="consultDialogVisible" width="800px" append-to-body>
      <el-table ref="consultTable" v-loading="loading" :data="consultDialogList" highlight-current-row
                @current-change="handleConsultCurrentChange" @row-click="handleConsultRowClick" border>
        <!-- 单选框列 -->
        <el-table-column width="55" align="center">
          <template slot-scope="scope">
            <el-radio :label="scope.row.consultId" v-model="selectedConsultId">{{ '' }}</el-radio>
          </template>
        </el-table-column>

        <el-table-column label="咨询号" align="center" prop="travelConsult.consultNumber" />
        <el-table-column label="客户姓名" align="center" prop="travelClient.clientName" />
        <el-table-column label="手机号" align="center" prop="travelClient.clientTel" />
        <el-table-column label="意向目的地" align="center" prop="travelConsult.preferredDestination" />
        <el-table-column label="预计出发时间" align="center" prop="travelConsult.estimatedTime" />
        <el-table-column label="定制师" align="center">
          <template slot-scope="scope">
            <!-- 从映射中获取姓名，默认显示"未分配" -->
            {{ designerNameMap[scope.row.travelConsult.designerId] || '未知定制师' }}
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="consultDialogTotal > 0" :total="consultDialogTotal"
                  :page.sync="consultDialogQueryParams.pageNum" :limit.sync="consultDialogQueryParams.pageSize"
                  @pagination="getConsultDialogList" />

      <div slot="footer" class="dialog-footer">
        <el-button @click="consultDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmConsultSelection" :disabled="!selectedConsultId">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="选择地陪" :visible.sync="guideDialogVisible" width="800px" append-to-body>
      <!-- 搜索栏 -->
      <el-form :model="guideQueryParams" ref="guideQueryForm" size="small" :inline="true" label-width="60px">
        <el-form-item label="姓名">
          <el-input v-model="guideQueryParams.nickName" placeholder="请输入姓名" clearable
                    @keyup.enter.native="getGuideUserList" style="width: 200px" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="guideQueryParams.phonenumber" placeholder="请输入手机号" clearable
                    @keyup.enter.native="getGuideUserList" style="width: 200px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="getGuideUserList">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetGuideQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 地陪用户列表（修改为单选模式） -->
      <el-table ref="guideTable" v-loading="guideLoading" :data="guideUserList" highlight-current-row
                @current-change="handleGuideCurrentChange" @row-click="handleGuideRowClick" style="margin-top: 10px" border>
        <!-- 单选框列 -->
        <el-table-column width="55" align="center">
          <template slot-scope="scope">
            <el-radio :label="scope.row.userId" v-model="selectedGuideId">{{ '' }}</el-radio>
          </template>
        </el-table-column>
        <el-table-column label="序号" type="index" align="center" />
        <el-table-column label="姓名" align="center" prop="nickName" />
        <el-table-column label="手机号" align="center" prop="phonenumber" />
        <el-table-column label="性别" align="center" prop="sex">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.sex" />
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status" />
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination v-show="guideTotal > 0" :total="guideTotal" :page.sync="guideQueryParams.pageNum"
                  :limit.sync="guideQueryParams.pageSize" @pagination="getGuideUserList" />

      <div slot="footer" class="dialog-footer">
        <el-button @click="guideDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmGuideSelection" :disabled="!selectedGuideId">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listSchedule,
  delSchedule,
  addSchedule,
  updateSchedule,
  listConsultByDesigner,
  getScheduleDetail
} from '@/api/travel/schedule'
import { listConsult } from '@/api/travel/consult'
import { listClient } from '@/api/travel/client'
import { getUserProfile, listGuiderUser ,listUser} from '@/api/system/user'
import { batchSaveScheduleContent, getContent, delAllContent } from '@/api/travel/schedule/content'
import { addOrder } from '@/api/travel/order'

export default {
  name: 'Schedule',
  dicts: ['travel_schedule_status', 'sys_user_sex', 'sys_normal_disable'],
  computed: {
    isConsultSelected() {
      return !!this.dialogForm.travelConsult?.consultNumber//若 this.dialogForm.travelConsult 存在，则返回 consultNumber 的值。不存在也不会跑错
    },
    guideNameMap() {
      return this.guideUserList.reduce((map, item) => {
        map[item.userId] = item.nickName
        return map
      }, {})
    }
  },
  watch: {
    'dialogForm.scheduleContents': {
      deep: true,//深度监听
      handler(val) {
        val.forEach((content, index) => {
          // 当开始时间或结束时间变化时，触发对应字段的验证
          if (content.startTime || content.endTime) {
            this.$refs.form.validateField(`scheduleContents[${index}].startTime`)
            this.$refs.form.validateField(`scheduleContents[${index}].endTime`)
          }
          // 当金额变化时，触发金额验证
          if (content.travelMoney !== null) {
            this.$refs.form.validateField(`scheduleContents[${index}].travelMoney`)
          }
          if (content.serviceMoney !== null) {
            this.$refs.form.validateField(`scheduleContents[${index}].serviceMoney`)
          }
        })
      }
    }
  },
  watch: {
    '$route.query.clientId': {
      immediate: true,//初始化时候执行一次
      handler(newVal) {
        this.clientId = newVal || null
        this.queryParams.clientId = this.clientId
        this.queryParams.pageNum = 1
        this.getList()
      }
    }
  },
  data() {
    return {
      userList: [], // 存储所有用户数据（含定制师）
      designerNameMap: {}, // 映射：ID ->系统用户 姓名
      selectedConsultId: null,
      selectedGuideId: null,
      clientId: null,//获取到客户id了
      isDetailMode: false, // 新增：是否为详情模式（true=只读，false=可编辑）

      //对角色显示哪些按钮，初始值为false根据不同的角色这个值会变成true
      isRoleEditPermission: false,
      isRoleDeletePermission: false,
      isRoleDesignerPermission: false,
      isRoleDetailPermission: false,
      isRoleRejectPermission: false,
      isRoleSignPermission: false,
      isRoleSubmitPermission: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 行程管理表格数据
      scheduleList: [],
      consultList: [],
      clientList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      currentUserId: null,
      currentUserRoleName: '',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        scheduleNumber: null,
        consultId: null,
        guideId: null,
        status: null,
        isDeleted: null,
        travelMoneyTotal: null,
        serviceMoneyTotal: null,
        moneyTotal: null,
        'travelConsult.consultNumber': null,
        'travelConsult.designerId': null,
        'travelClient.clientTel': null,
        userId: this.currentUserId,  //userId放入查询参数里面
        userRoleName: this.currentUserRoleName,
        clientId: this.clientId
      },
      dialogForm: {
        // 行程基本信息
        scheduleId: null,
        scheduleNumber: null,
        consultId: null,
        guideId: null,
        status: null,
        travelMoneyTotal: null,
        serviceMoneyTotal: null,
        moneyTotal: null,
        isDeleted: 0, // 默认未删除
        // 咨询信息（嵌套对象必须初始化）
        travelConsult: {
          consultNumber: null,
          travelerCount: null,
          preferredDestination: null,
          budget: null,
          estimatedTime: null,
          flexibleDays: null,
          plannedDays: null,
          designerId: null
        },
        // 客户信息（嵌套对象必须初始化）
        travelClient: {
          clientName: null,
          clientTel: null
        },
        //只要它在 data() 里，Vue 就会自动把它变成响应式，数组本身和数组里的对象属性都会实时驱动 DOM 变化。
        scheduleContents: [ // 存储所有行程内容（初始包含1个空内容）
          {
            scheduleContentId: null,
            scheduleContentName: '1',
            scheduleId: null,
            startTime: '',
            endTime: '',
            travelMoney: null,
            serviceMoney: null,
            picture1: null,
            picture2: null,
            picture3: null,
            scheduleContent: null,
            remark: null
          }
        ]
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        consultId: [{ required: true, message: '咨询号不能为空', trigger: 'blur' }],
        status: [{ required: true, message: '状态不能为空', trigger: 'change' }],
        scheduleContentRules: {
          startTime: [
            {
              validator: (rule, value, callback) => {
                const index = parseInt(rule.field.split('[')[1].split(']')[0])//字段提取索引，得到当前验证字段在 scheduleContents 数组中的索引（如 0、1 等）。
                const content = this.dialogForm.scheduleContents[index]
                const isEmptyContent = !content.startTime && !content.endTime &&
                  !content.scheduleContent && content.travelMoney === null &&
                  content.serviceMoney === null
/*
核心逻辑：如果整行数据不全为空（即用户填写了某些字段），但开始时间为空，则抛出错误提示 “开始时间不能为空”。
只要用户填写了任意一个字段（如结束时间、行程内容等），那么开始时间就必须填写。
只有当整行所有字段都没填时，才会被视为 “空行”，从而跳过对开始时间的验证。
 */
                if (!isEmptyContent && !value) {
                  return callback(new Error('开始时间不能为空'))
                }

                // 开始时间不为空且结束时间也不为空时，校验时间顺序
                if (value && content.endTime && new Date(value) >= new Date(content.endTime)) {
                  return callback(new Error('开始时间不能晚于结束时间'))
                }

                callback()
              },
              trigger: 'change'
            }
          ],
          endTime: [
            {
              validator: (rule, value, callback) => {
                const index = parseInt(rule.field.split('[')[1].split(']')[0])
                const content = this.dialogForm.scheduleContents[index]
                const isEmptyContent = !content.startTime && !content.endTime &&
                  !content.scheduleContent && content.travelMoney === null &&
                  content.serviceMoney === null

                if (!isEmptyContent && !value) {
                  return callback(new Error('结束时间不能为空'))
                }

                // 新增：结束时间不为空且开始时间也不为空时，校验时间顺序
                if (value && content.startTime && new Date(value) <= new Date(content.startTime)) {
                  return callback(new Error('结束时间必须晚于开始时间'))
                }

                callback()
              },
              trigger: 'change'
            }
          ],
          scheduleContent: [
            {
              validator: (rule, value, callback) => {
                const index = parseInt(rule.field.split('[')[1].split(']')[0])
                const content = this.dialogForm.scheduleContents[index]
                const isEmptyContent = !content.startTime && !content.endTime &&
                  !content.scheduleContent && content.travelMoney === null &&
                  content.serviceMoney === null

                if (!isEmptyContent && !value) {
                  callback(new Error('行程详情不能为空'))
                } else {
                  callback()
                }
              },
              trigger: 'blur'
            }
          ],
          travelMoney: [
            {
              validator: (rule, value, callback) => {
                const index = parseInt(rule.field.split('[')[1].split(']')[0])
                const content = this.dialogForm.scheduleContents[index]
                const isEmptyContent = !content.startTime && !content.endTime &&
                  !content.scheduleContent && content.travelMoney === null &&
                  content.serviceMoney === null

                if (!isEmptyContent && value === null) {
                  return callback(new Error('旅行费用不能为空'))
                }

                // 新增：数字校验（允许整数或小数，最多两位小数）
                if (value !== null && !/^\d+(\.\d{1,2})?$/.test(value.toString())) {
                  return callback(new Error('请输入有效的金额（最多两位小数）'))
                }

                callback()
              },
              trigger: 'blur'
            }
          ],
          serviceMoney: [
            {
              validator: (rule, value, callback) => {
                const index = parseInt(rule.field.split('[')[1].split(']')[0])
                const content = this.dialogForm.scheduleContents[index]
                const isEmptyContent = !content.startTime && !content.endTime &&
                  !content.scheduleContent && content.travelMoney === null &&
                  content.serviceMoney === null

                if (!isEmptyContent && value === null) {
                  return callback(new Error('服务费用不能为空'))
                }

                // 新增：数字校验（允许整数或小数，最多两位小数）
                if (value !== null && !/^\d+(\.\d{1,2})?$/.test(value.toString())) {
                  return callback(new Error('请输入有效的金额（最多两位小数）'))
                }

                callback()
              },
              trigger: 'blur'
            }
          ]
        }
      },

      // 咨询选择对话框
      consultDialogVisible: false,
      // 选中的咨询信息
      selectedConsult: null,
      // 咨询列表查询参数（简化版，仅保留分页）
      consultDialogQueryParams: {
        pageNum: 1,
        pageSize: 10,
        'travelConsult.designerId': null
      },
      // 咨询列表总数
      consultDialogTotal: 0,
      // 咨询列表数据
      consultDialogList: [],

      // 新增：地陪选择对话框相关
      guideDialogVisible: false, // 对话框显示状态
      guideLoading: false, // 列表加载状态
      guideUserList: [], // 地陪用户列表
      guideTotal: 0, // 总条数
      selectedGuide: null, // 选中的地陪
      currentScheduleId: null, // 当前操作的行程ID
      // 地陪查询参数
      guideQueryParams: {
        pageNum: 1,
        pageSize: 10,
        nickName: null, // 姓名搜索
        phonenumber: null // 手机号搜索
      }
    }
  },
  created() {
    this.loadAllUsers(); // 新增：加载所有用户数据
    // 在生命周期钩子中获取参数
    console.log('接收的客户ID:', this.$route.query.clientId)
    this.clientId = this.$route.query.clientId || null
    // 关键：将clientId绑定到查询参数
    this.queryParams.clientId = this.clientId

    this.getUserInfo()
    this.getGuideUserList()

    // 获取当前登录用户ID并保存
    console.log('DictTag options:', this.options)
  },
  // 在 mounted 或初始化时调用
  mounted() {
    this.calculateTotalFees()
  },
  methods: {
    // 加载所有用户数据（用于构建映射）
    loadAllUsers() {
      listUser({ pageNum: 1, pageSize: 1000 }).then(response => { // 假设listUser可获取所有用户
        this.userList = response.rows;
        // 构建映射：key=用户ID，value=用户姓名
        this.designerNameMap = this.userList.reduce((map, user) => {
          map[user.userId] = user.nickName || user.userName; // 优先用nickName，无则用userName
          return map;
        }, {});
      }).catch(error => {
        console.error('加载用户数据失败:', error);
      });
    },

    handleConsultCurrentChange(currentRow) {
      this.selectedConsult = currentRow
    },

    // 单选框处理行点击选中/取消
    handleConsultRowClick(row) {
      // 点击已选中的行则取消选中
      if (this.selectedConsult && this.selectedConsult.consultId === row.consultId) {
        this.selectedConsult = null
        this.$refs.consultTable.setCurrentRow(null) // 取消高亮
      } else {
        this.selectedConsult = row
        this.$refs.consultTable.setCurrentRow(row) // 高亮当前行
      }
    },
    handleGuideCurrentChange(currentRow) {
      this.selectedGuide = currentRow
    },

    handleGuideRowClick(row) {
      // 点击已选中的行则取消选中，如果已经选中，并且正在改这行
      if (this.selectedGuide && this.selectedGuide.userId === row.userId) {
        this.selectedGuide = null//通过表格的 setCurrentRow 方法，取消当前行的高亮显示（视觉上取消选中效果）。
        this.$refs.guideTable.setCurrentRow(null)  // 取消高亮 通过表格的 setCurrentRow 方法，取消当前行的高亮显示（视觉上取消选中效果）。
      } else {
        this.selectedGuide = row
        this.$refs.guideTable.setCurrentRow(row)  // 高亮当前行
      }
    },
    // 哪种角色可以看到详情
    showDetailButton(row) {
      const role = this.currentUserRoleName
      const status = row.status
      // 超级管理员总能看到
      if (role === '超级管理员') return true

      // 客服在所有状态都能看到
      if (role === '客服') return true

      // 定制师在草稿和自己的已签约状态能看到
      if (role === '定制师') return true

      // 地陪在待签约和已签约且属于自己时能看到
      if (role === '地陪') {
        return status === '1' || status === '2'
      }

      return false
    },

    // 判断是否显示修改按钮
    showEditButton(row) {
      const role = this.currentUserRoleName
      const status = row.status

      // 超级管理员总能看到
      if (role === '超级管理员') return true

      // 定制师在草稿状态且是自己的行程单
      return role === '定制师' && status === '0'
    },

    // 判断是否显示删除按钮
    showDeleteButton(row) {
      const role = this.currentUserRoleName
      const status = row.status

      // 超级管理员总能看到
      if (role === '超级管理员') return true

      // 定制师在草稿状态且是自己的行程单
      return role === '定制师' && status === '0'
    },

    // 判断是否显示提交按钮
    showSubmitButton(row) {
      const role = this.currentUserRoleName
      const status = row.status

      // 超级管理员总能看到
      if (role === '超级管理员' && status === '0') return true

      // 定制师在草稿状态且是自己的行程单
      return role === '定制师' && status === '0'
    },

    // 判断是否显示退回按钮
    showRejectButton(row) {
      const role = this.currentUserRoleName
      const status = row.status

      // 超级管理员总能看到
      if (role === '超级管理员' && status === '1') return true

      // 客服在待签约状态
      return role === '客服' && status === '1'
    },

    // 判断是否显示签约按钮
    showSignButton(row) {
      const role = this.currentUserRoleName
      const status = row.status

      // 超级管理员总能看到
      if (role === '超级管理员' && status === '1') return true

      // 客服在待签约状态
      return role === '客服' && status === '1'
    },

    // 判断是否显示分配地陪按钮
    showAssignButton(row) {
      const role = this.currentUserRoleName
      const status = row.status

      // 超级管理员总能看到
      if (role === '超级管理员' && status === '1') return true

      // 客服在待签约状态
      return role === '客服' && status === '1'
    },

    // 查看详情
    handleDetail(row) {
      this.resetDialogForm() // 重置表单
      this.isDetailMode = true // 开启详情模式（只读）
      this.title = '行程详情' // 修改对话框标题
      this.open = true // 显示对话框

      // 加载行程详情
      this.loadScheduleDetail(row.scheduleId)
    },
    // 根据 guideId 获取地陪姓名
    getGuideName(guideId) {
      return guideId ? this.guideNameMap[guideId] || '未知地陪' : '未分配'
    },
    // 计算所有行程内容的费用合计
    calculateTotalFees() {
      const contents = this.dialogForm.scheduleContents
      // 累加旅行费用和服务费用,reduce数组的累加器
      /*
      reduce 方法：数组的累加器方法，接收两个参数：
      第一个参数：回调函数（用于计算累加逻辑）。
      第二个参数：初始值（这里是 0，表示从 0 开始累加）。

      回调函数 (sum, item) => { ... } 有两个参数：
sum：累加的中间结果（上一次计算的总和）。
item：当前遍历到的数组元素（即当前行程对象）。parseFloat(无论什么类型都变成浮点数
       */
      const travelTotal = contents.reduce((sum, item) => {
        return sum + (parseFloat(item.travelMoney) || 0)
      }, 0)

      const serviceTotal = contents.reduce((sum, item) => {
        return sum + (parseFloat(item.serviceMoney) || 0)
      }, 0)
      // 更新到表单中
      this.dialogForm.travelMoneyTotal = travelTotal.toFixed(2)
      this.dialogForm.serviceMoneyTotal = serviceTotal.toFixed(2)
      this.dialogForm.moneyTotal = (travelTotal + serviceTotal).toFixed(2)
    },
    // 获取当前登录用户信息
    getUserInfo() {
      try {
        getUserProfile().then(userProfileRes => {
          console.log(userProfileRes)
          // 保存当前用户的 userId 到变量中
          this.currentUserId = userProfileRes.data.userId
          this.currentUserRoleName = userProfileRes.data.roles[0].roleName
          console.log(userProfileRes.data.roles[0].roleName)

          // 2. 给 queryParams 赋值（关键：在异步请求完成后再赋值）
          this.queryParams.userId = this.currentUserId
          this.queryParams.userRoleName = this.currentUserRoleName
          this.queryParams.clientId = this.clientId || this.$route.query.clientId || null
          // 3. 调用 getList 加载数据（此时参数已正确赋值）
          this.getList()
        })
      } catch (error) {
        console.error('获取当前用户信息失败：', error)
        this.$message.error('获取用户信息失败，请刷新页面重试')
      }
    },
    /** 查询行程管理列表 */
    getList() {
      this.loading = true
      console.log(this.queryParams)
      listSchedule(this.queryParams).then(response => {
        this.scheduleList = response.rows
        this.total = response.total
        this.loading = false
        this.loadAllUsers();//如果用户发生变化的话
      })
    },
//只是显示列表没有过滤条件
    // 打开咨询选择对话框
    openConsultDialog() {
      this.selectedConsult = null
      this.consultDialogVisible = true
      // 赋值 designerId 为当前登录用户ID
      this.consultDialogQueryParams['travelConsult.designerId'] = this.currentUserId
      this.getConsultDialogList()
    },

    // 获取咨询列表数据
    getConsultDialogList() {
      this.loading = true
      listConsultByDesigner(this.consultDialogQueryParams).then(response => {
        this.consultDialogList = response.rows
        this.consultDialogTotal = response.total
        this.loading = false
      }).catch(error => {
        console.error('获取咨询列表失败:', error)
        this.loading = false
      })
    },
    // 确认选择咨询
    confirmConsultSelection() {
      if (!this.selectedConsultId) {
        this.$message.warning('请选择一个咨询记录')
        return
      }

      // 1. 根据 ID 找到整行
      const row = this.consultDialogList.find(item => item.consultId === this.selectedConsultId)

      // 2. 回填到表单
      this.dialogForm.consultId = this.selectedConsultId
      this.dialogForm.travelConsult = row.travelConsult || row
      this.dialogForm.travelClient = row.travelClient
      this.dialogForm.clientId = row.clientId || row.travelClient?.clientId

      this.consultDialogVisible = false
    },
    // 表单重置
    reset() {
      this.form = {
        scheduleId: null,
        scheduleNumber: null,
        consultId: null,
        guideId: null,
        status: null,
        createBy: null,
        updateBy: null,
        createTime: null,
        updateTime: null,
        remark: null,
        isDeleted: null,
        travelMoneyTotal: null,
        serviceMoneyTotal: null,
        moneyTotal: null,
        clientId: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.queryParams['travelClient.clientTel'] = null
      this.queryParams['travelConsult.consultNumber'] = null
      // 关键：清除clientId参数
      this.queryParams.clientId = null
      this.clientId = null

      // 如果是从其他页面带clientId跳转过来的，清除路由参数
      if (this.$route.query.clientId) {
        this.$router.replace({
          path: this.$route.path,
          query: {}
        })
      }
      //无参数状态
      this.handleQuery()
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.scheduleId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    //新增按钮操作
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加行程管理'
      this.isDetailMode = false // 重置为编辑模式
      // 重置为只有一个空内容
      this.dialogForm.scheduleContents = [
        {
          scheduleContentId: null,
          scheduleContentName: '1',
          scheduleId: null,
          startTime: '',
          endTime: '',
          travelMoney: null,
          serviceMoney: null,
          picture1: null,
          picture2: null,
          picture3: null,
          scheduleContent: null,
          remark: null
        }
      ]
      // 重置表单（包含费用字段）
      this.resetDialogForm();
      // 强制计算初始费用（此时行程内容为空，结果应为0.00）
      this.calculateTotalFees();
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      // 统一变量名：获取单个ID或批量选中的ID数组
      const scheduleIds = row ? row.scheduleId : this.ids;
      // 处理批量删除时的显示文本（数组转字符串）
      const displayIds = Array.isArray(scheduleIds) ? scheduleIds.join(',') : scheduleIds;

      this.$modal.confirm(`是否确认删除？`)
        // 使用箭头函数确保this指向组件实例
        .then(() => {
          // 调用删除接口（支持单个ID或ID数组）
          return delSchedule(scheduleIds);
        })
        .then(() => {
          this.getList(); // 刷新列表
          this.$modal.msgSuccess("删除成功");
        })
        .catch(error => {
          // 增加错误提示
          console.log('增加行程错误')
        });
    },

    // 重置对话框（清空动态内容）
    resetDialogForm() {
      this.dialogForm = {
        scheduleId: null,
        scheduleNumber: null,
        consultId: null,
        guideId: null,
        status: null,
        travelMoneyTotal: '0.00', // 显式重置为0.00
        serviceMoneyTotal: '0.00',
        moneyTotal: '0.00',
        isDeleted: 0,
        clientId: null,
        travelConsult: {
          consultNumber: null,
          travelerCount: null,
          preferredDestination: null,
          budget: null,
          estimatedTime: null,
          flexibleDays: null,
          plannedDays: null,
          designerId: null
        },
        travelClient: {
          clientName: null,
          clientTel: null
        },
        scheduleContents: [
          {
            scheduleContentId: null,
            scheduleId: null,
            scheduleContentName: '1',
            startTime: '',
            endTime: '',
            travelMoney: null,
            serviceMoney: null,
            picture1: null,
            picture2: null,
            picture3: null,
            scheduleContent: null,
            remark: null
          }
        ]
      }
      this.$refs.form && this.$refs.form.resetFields() //避免 “表单实例不存在”存在才会重置表单
    },

    // 检查指定索引的内容是否填写完整
    isContentValid(index) { //判断是不是为内容几是不是为空
      const content = this.dialogForm.scheduleContents[index]
      return !!content.startTime &&
        !!content.endTime &&
        !!content.scheduleContent &&
        content.travelMoney !== null &&
        content.serviceMoney !== null
      this.calculateTotalFees();
    },

    // 添加新内容
    addNewContent() {
      const lastIndex = this.dialogForm.scheduleContents.length - 1
      if (!this.isContentValid(lastIndex)) {
        this.$message.warning('请先完成当前内容的所有必填项')
        return
      }

      const newContentIndex = this.dialogForm.scheduleContents.length + 1
      this.dialogForm.scheduleContents.push({
        scheduleContentId: null,
        scheduleId: this.dialogForm.scheduleId,
        scheduleContentName: newContentIndex,
        startTime: '',
        endTime: '',
        travelMoney: null,
        serviceMoney: null,
        picture1: null,
        picture2: null,
        picture3: null,
        scheduleContent: null,
        remark: null
      })

      // 关键：使用setTimeout确保DOM完全渲染（比$nextTick更可靠）
      setTimeout(() => {
        // 通过ID直接定位新内容（绝对可靠）
        const newIndex = this.dialogForm.scheduleContents.length - 1
        const newContent = document.getElementById(`content-${newIndex}`)
        const container = document.querySelector('.dynamic-schedule-content')

        if (newContent && container) {
          // 计算新内容相对于容器的偏移量
          const containerRect = container.getBoundingClientRect()
          const contentRect = newContent.getBoundingClientRect()
          const offsetTop = contentRect.top - containerRect.top

          // 强制滚动（忽略浏览器默认行为）
          container.scrollTop = offsetTop + container.scrollTop

          // 聚焦到开始时间输入框（确保视觉反馈）
          // newContent.querySelector('.el-date-editor input')?.focus();
        }
      }, 100) // 100ms延迟确保DOM渲染完成
    },

    // 删除指定索引的内容
    deleteContent(index) {
      this.$confirm(`确定要删除第${index + 1}条行程内容吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.dialogForm.scheduleContents.splice(index, 1) //从行程内容数组中删除指定索引的内容
        // 重新更新所有内容的序号
        this.dialogForm.scheduleContents.forEach((item, i) => {
          item.scheduleContentName = (i + 1).toString()
        })//重新编号所有的内容
        this.calculateTotalFees()
        this.$message.success('删除成功')
      })
    },

    // 提交表单（保存行程+行程内容）
    submitDialogForm() {
      this.calculateTotalFees(); // 先确保总金额已计算
      console.log("前端提交的第一个行程内容开始时间：", this.dialogForm.scheduleContents[0]?.startTime);
      // 筛选有效内容
      const allContents = this.dialogForm.scheduleContents;
      const validContents = allContents.filter(content => {
        return content.startTime || content.endTime || content.scheduleContent ||
          content.travelMoney !== null || content.serviceMoney !== null;
      });
//提交表单的时候用的
      if (validContents.length === 0) {
        this.$message.error('至少需要添加一条行程内容');
        return;
      }

      // 验证表单
      this.$refs.form.validate(valid => {
        if (valid) {
          // validContents.forEach(item => {
          //   if (item.startTime) {
          //     item.startTime = new Date(item.startTime) // 或直接 this.$moment(item.startTime).format('YYYY-MM-DD HH:mm:ss')
          //   }
          //   if (item.endTime) {
          //     item.endTime = new Date(item.endTime)
          //   }
          // });
          const saveMainData = async () => {
            if (this.dialogForm.scheduleId) { // 修改操作
              // 1. 删除原有内容
              await delAllContent(this.dialogForm.scheduleId);
//validContents是过滤过数据合理的数组
              // 2. 保存新内容
              if (validContents.length > 0) {
                const newContents = validContents.map(item => ({
                  ...item,
                  scheduleId: this.dialogForm.scheduleId
                }));
                /*

                ...item：把每个内容对象里的 startTime / endTime / travelMoney … 全部展开到新对象。
scheduleId: xxx：给每条内容加上“它属于哪条行程”这个外键，方便后端插入。
                 */
                await batchSaveScheduleContent(newContents);
              }
/*
...item：使用扩展运算符复制原有行程内容的所有属性（避免修改原数组）。
scheduleId: this.dialogForm.scheduleId：给每个内容添加 scheduleId（当前行程的 ID）
 */
              // 3. 同步更新主表（travel_schedule）的总金额
              const updateData = {
                scheduleId: this.dialogForm.scheduleId,
                travelMoneyTotal: this.dialogForm.travelMoneyTotal, // 旅行总费用
                serviceMoneyTotal: this.dialogForm.serviceMoneyTotal, // 服务总费用
                moneyTotal: this.dialogForm.moneyTotal, // 总费用合计

              };
              await updateSchedule(updateData); // 调用主表更新接口

              return true;
            } else { // 新增操作（原有逻辑包含主表创建）
              return addSchedule({
                ...this.dialogForm,

              }).then(response => { //先创建主表 ，获取新创建的行程ID
                const scheduleId = response.data.scheduleId;
                return batchSaveScheduleContent(
                  validContents.map(item => ({ ...item, scheduleId })) //// 为每个内容添加行程ID
                );
              });
            }
          };

          // 执行保存逻辑（不变）
          saveMainData().then(() => {
            this.$message.success(this.dialogForm.scheduleId ? '修改成功' : '新增成功');
            this.open = false;
            this.getList();
            this.resetDialogForm();
          }).catch(error => {
            this.$message.error('保存失败: ' + (error.response?.data?.msg || error.message));
          });
        }
      });
    },

    // 取消按钮（重置动态内容）
    cancel() {
      this.open = false
      this.resetDialogForm()
      this.reset()
      this.isDetailMode = false // 重置为编辑模式
    },

    handleImageSuccess(response, contentIndex, pictureIndex) {
      console.log('上传响应数据：', response)
      console.log('上传响应数据：', response.url)
      if (response.code === 200) {
        this.dialogForm.scheduleContents[contentIndex][`picture${pictureIndex}`] = response.url
        this.$message.success('上传成功')
      } else {
        this.$message.error('上传失败：' + response.msg)
      }
    },

    // 图片上传前校验（Vue2 兼容版）
    beforeImageUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('只能上传JPG/PNG格式的图片!')
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过2MB!')
      }
      return isJPG && isLt2M
    },

    // 加载行程详情（分两步：先主信息，再内容列表）
    async loadScheduleDetail(scheduleId) {
      try {
        this.loading = true;

        // 获取行程主信息,getScheduleDetail是这个方法相应的data
        const scheduleRes = await getScheduleDetail(scheduleId);
        const scheduleData = scheduleRes.data;

        // 获取行程内容列表
        const contentRes = await getContent(scheduleId);
        const contentList = contentRes.data || [];

        //将行程内容列表进行过滤formatContentList的结果
        // 强制把后端返回的时间字符串转成前端需要的字符串格式
        const formatContentList = contentList.map(item => ({
          ...item,
          // 如果后端返回的是 "2025-07-17T14:30:00" 这种格式，直接保留
          // 如果后端返回的是时间戳或 Date 对象，再格式化
          startTime: item.startTime || '',
          endTime: item.endTime || ''
        }));
//有效值就是正确时间，无效就是代码
        // 填充基础信息
        this.dialogForm = {
          scheduleId: scheduleData.scheduleId,
          scheduleNumber: scheduleData.scheduleNumber,
          consultId: scheduleData.consultId,
          guideId: scheduleData.guideId,
          status: scheduleData.status,
          travelMoneyTotal: scheduleData.travelMoneyTotal || '0.00',
          serviceMoneyTotal: scheduleData.serviceMoneyTotal || '0.00',
          moneyTotal: scheduleData.moneyTotal || '0.00',
          isDeleted: scheduleData.isDeleted || 0,
          clientId: scheduleData.clientId,
          travelConsult: scheduleData.travelConsult || {
            consultNumber: null,
            travelerCount: null,
            preferredDestination: null,
            budget: null,
            estimatedTime: null,
            flexibleDays: null,
            plannedDays: null,
            designerId: null
          },
          travelClient: scheduleData.travelClient || {
            clientName: null,
            clientTel: null
          },
          //确保表单中至少有一个空的行程内容项
          scheduleContents:
            formatContentList.length > 0 //// 判断后端返回的行程内容是否为空
              ? formatContentList //// 若不为空，使用后端数据
              : [ //// 若为空，创建一个默认的空内容项
                {
                  scheduleContentId: null,
                  scheduleId: scheduleData.scheduleId,
                  startTime: '',
                  endTime: '',
                  travelMoney: null,
                  serviceMoney: null,
                  picture1: null,
                  picture2: null,
                  picture3: null,
                  scheduleContent: null,
                  remark: null
                }
              ]
        };

        this.open = true;
        this.title = this.isDetailMode ? '行程详情' : '修改行程管理';
        this.loading = false;
        this.calculateTotalFees();
      } catch (error) {
        console.error('加载行程详情失败:', error);
        this.$message.error('加载行程详情失败，请重试');
        this.loading = false;
      }
    },

    // 修改按钮点击事件（触发回显）
    handleUpdate(row) {
      this.resetDialogForm()// 先重置表单
      this.isDetailMode = false // 重置为编辑模式
      const scheduleId = row?.scheduleId || this.ids// 获取选中的行程ID
      if (!scheduleId) {
        this.$message.warning('请选择一条行程')
        return
      }
      //有了scheduleId,把这个参数传进去loadScheduleDetail
      this.loadScheduleDetail(scheduleId)// 调用回显方法
    },

    // 新增：打开地陪选择对话框
    handleDesigner(row) {
      this.currentScheduleId = row.scheduleId // 记录当前行程ID
      this.selectedGuide = null // 重置选中状态
      this.guideDialogVisible = true // 显示对话框
      this.getGuideUserList() // 加载地陪列表
    },

    // 新增：获取地陪用户列表（角色为地陪的sys_user）
    getGuideUserList() {
      this.guideLoading = true
      // 调用后端接口（假设方法名为listGuideUser）
      console.log(this.guideQueryParams)
      listGuiderUser(this.guideQueryParams).then(response => {
        console.log(response)
        this.guideUserList = response.rows
        this.guideTotal = response.total
        this.guideLoading = false
      }).catch(error => {
        console.error('获取地陪列表失败:', error)
        this.guideLoading = false
      })
    },

    // 新增：确认选择地陪
    confirmGuideSelection() {
      if (!this.selectedGuideId) {
        this.$message.warning('请选择一个地陪')
        return
      }

      const row = this.guideUserList.find(item => item.userId === this.selectedGuideId)

      updateSchedule({
        scheduleId: this.currentScheduleId,
        guideId: this.selectedGuideId,
      }).then(response => {
        this.$message.success('地陪设置成功')
        this.guideDialogVisible = false
        this.getList()
      }).catch(error => {
        this.$message.error('设置失败: ' + (error.response?.data?.msg || error.message))
      })
    },
    //通用弹窗提示
    confirmAction(message) {
      return this.$confirm(message, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      });
    },
    // 新增：重置地陪查询参数
    resetGuideQuery() {
      this.guideQueryParams = {
        pageNum: 1,
        pageSize: 10,
        nickName: null,
        phonenumber: null
      }
      this.getGuideUserList()
    },
//提交操作
    async handleSubmit(row) {
      await this.confirmAction('确定要提交该行程吗？');
      console.log(row)
      const updateData = {
        scheduleId: row.scheduleId,
        status: 1
      }
      updateSchedule(updateData).then(response => {
        this.$message.success('草稿提交成功')
        this.guideDialogVisible = false
        this.getList() // 刷新行程列表
      }).catch(error => {
        this.$message.error('提交失败: ' + (error.response?.data?.msg || error.message))
      })
    },
    //退回操作
    async handleReject(row) {
      await this.confirmAction('确定要退回该行程吗？');
      console.log(row)
      const updateData = {
        scheduleId: row.scheduleId,
        status: 0
      }
      updateSchedule(updateData).then(response => {
        this.$message.success('退回成功')
        this.guideDialogVisible = false
        this.getList() // 刷新行程列表
      }).catch(error => {
        this.$message.error('退回失败: ' + (error.response?.data?.msg || error.message))
      })
    },
//签约操作
    async handleSign(row) {
      await this.confirmAction('确定要签约该行程吗？');
      console.log(row)
      const updateData = {
        scheduleId: row.scheduleId,
        status: 2
      }

      updateSchedule(updateData).then(response => {
        this.$message.success('签约成功')
        this.getList() // 刷新行程列表
      }).catch(error => {
        this.$message.error('签约失败: ' + (error.response?.data?.msg || error.message))
      })
      //新建订单
      const addOrderData = {
        scheduleId: row.scheduleId,
        status: 0,
        moneyTotal: row.moneyTotal,
        clientId: row.clientId
      }
      addOrder(addOrderData).then(response => {
        this.$message.success('形成相应订单')
      }).catch(error => {
        this.$message.error('形成相应订单失败: ' + (error.response?.data?.msg || error.message))
      })
    }

  }

}
</script>
<style scoped>
/* 新增外层容器样式 */
/* 只保留基础布局样式，删除所有高度和定位限制 */
.dynamic-schedule-wrapper {
  margin-top: 20px;
}

/* 确保没有以下样式干扰 */
.dynamic-schedule-content {
  overflow-y: auto !important;
  /* 强制允许滚动 */
  max-height: 600px !important;
  /* 给一个合理的最大高度，确保内容溢出时可滚动 */
}

.step-content {
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  padding: 15px;
  margin-bottom: 15px;
  background-color: #fff;
}

/* 费用区域样式简化 */
.total-fee-container {
  padding: 10px 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border: 1px solid #e6e6e6;
  margin-bottom: 20px;
}

.step-content {
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  padding: 15px;
  margin-bottom: 15px;
  background-color: #fff;
}

.step-content:last-child {
  margin-bottom: 0;
}

/* 时间选择和费用输入的行布局 */
.mb4 {
  margin-bottom: 16px;
}

/* 图片上传样式（Vue2 Element UI 兼容版） */
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
}

/* 原样式保留，新增穿透样式 */
::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

::v-deep .avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

::v-deep .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
  object-fit: cover;
  /* 新增：图片自适应填充 */
}

.mb4 {
  margin-bottom: 16px;
}

.total-fee-container .el-input {
  font-weight: bold;
  color: #1890ff;
}

/* 新增按钮组样式 */
.content-actions {
  display: flex;
  /* 横向排列按钮 */
  justify-content: flex-end;
  /* 右对齐 */
  margin-top: 15px;
  /* 与上方内容保持距离 */
  gap: 10px;
  /* 按钮之间的间距 */
}

/* 隐藏单选框的文字标签（统一设置） */
.el-radio__label {
  display: none !important;
}

</style>
